<template>
  <div class="TestArea">
    <!-- <p>visualseries:{{ visualseries }}</p> -->
    <!-- <p>scaleErrorId:{{ scaleErrorId }}</p>
    <p>scaleErrorData:{{ scaleErrorData }}</p> -->
    <!-- <p>TaskErrorData:{{ TaskErrorData }}</p>
    <p>TaskErrorDataArray:{{ TaskErrorDataArray }}</p>
    <p>chekedTaskErrorData:{{ chekedTaskErrorData }}</p> -->
    <!-- <p>remainParms:{{ remainParms }}</p> -->
    <!-- <p>markAreaDataArray:{{ markAreaDataArray }}</p> -->
    <!-- <p>checkedParms:{{ checkedParms }}</p> -->
    <!-- <p>TaskUserList:{{ TaskUserList }}</p> -->
    <!-- <p>checkedFilteredColumnList:{{ checkedFilteredColumnList }}</p>
    <p>checkedFilteredTableData:{{ checkedFilteredTableData }}</p> -->
    <!-- <p>preFilterData:{{ preFilterData }}</p> -->
    <!-- <p>preFilterData[0]:{{ preFilterData[0] }}</p> -->
    <!-- <p>checkedData:{{ checkedData }}</p> -->
    <!-- <p>markColumns:{{ markColumns }}</p> -->
    <!-- <p>sourcetitle:{{ sourcetitle }}</p> -->
    <!-- <p>datasetSource:{{ datasetSource }}</p> -->
    <!-- <p>source_copy:{{ source_copy }}</p> -->
    <!-- <p>preFilterTableData:{{ preFilterTableData }}</p> -->
    <!-- <p>preFilterColumnList:{{ preFilterColumnList }}</p> -->
    <!-- <p>dynamicswitchesData:{{ dynamicswitchesData }}</p> -->
    <!-- <p>FilterParmsTree:{{ FilterParmsTree }}</p> -->
    <!-- <p>allLeafParms:{{ allLeafParms }}</p> -->
    <!-- <p>offLineDataFileOptions:{{ offLineDataFileOptions }}</p>
    <p>checkedDataFile:{{ checkedDataFile }}</p> -->
  </div>
  <!-- 数据源切换 -->
  <div class="DataSourceSwitch" style="margin: 10px">
    <el-row :gutter="18">
      <el-col :span="1" />
      <el-col :span="3">
        <el-form-item label="选择数据源:">
          <el-select
            v-model="currentDataSource"
            placeholder="选择数据源"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in DataSourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <div class="onLineArea" v-if="currentDataSource == 'onLineDataSource'">
          <!-- 在线数据 -->
          <!-- {{ TimeRange }} -->
          <el-form-item label="选择时间范围:">
            <el-date-picker
              v-model="TimeRange"
              type="datetimerange"
              range-separator="--"
              start-placeholder="起始时间"
              end-placeholder="结束时间"
              format="YYYY/MM/DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="max-width: 500px"
            />
            <el-button
              type="primary"
              style="margin-left: 10px"
              @click="getOnlineData()"
              >拉取数据</el-button
            >
          </el-form-item>
        </div>
        <!-- 离线数据 -->
        <div class="offLineArea" v-else>
          <el-form-item label="选择离线文件:">
            <el-select
              v-model="checkedDataFile"
              placeholder="Select"
              clearable
              size="large"
              style="width: 240px"
            >
              <el-option
                v-for="item in offLineDataFileOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
              <template #footer>
                <el-button
                  text
                  type="primary"
                  bg
                  size="small"
                  @click="uploadFileDialogVisible = true"
                >
                  上传离线文件
                </el-button>
              </template>
            </el-select>
            <el-form-item label="选择时间范围:" style="margin-left: 10px">
              <el-date-picker
                v-model="csvTimeRange"
                type="datetimerange"
                range-separator="--"
                start-placeholder="起始时间"
                end-placeholder="结束时间"
                :disabled-date="disabledDate"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-button style="margin-left: 10px" @click="getOfflineData()"
              >获取数据</el-button
            >
          </el-form-item>
        </div>
      </el-col>
    </el-row>
  </div>
  <div class="WorkTableChart" style="margin: 10px">
    <el-row :gutter="10">
      <!-- 左侧--参数区 -->
      <el-col :span="4">
        <!-- 左侧--树状参数 -->
        <div class="FilterParmsTree">
          <el-input
            v-model="filterText"
            style="max-width: 300px"
            placeholder="Filter keyword"
          />
          <el-tree
            ref="FilterParmsTreeRef"
            class="filter-tree"
            style="max-width: 600px"
            :data="FilterParmsTree"
            node-key="id"
            :props="defaultProps"
            show-checkbox
            default-expand-all
            :filter-node-method="filterNode"
            @check-change="handleCheckChange"
          />
        </div>
        <div class="BtnArea">
          <div class="confirmBtn">
            <el-button type="primary" plain @click="getCheckedData()"
              >拉取曲线</el-button
            >
          </div>
          <div class="addParmsBtn">
            <el-button
              type="success"
              plain
              @click="
                chooseParmsDialogVisible = true;
                getRemainParms();
              "
              >添加参数</el-button
            >
            <!-- 弹框内容 -->
            <el-dialog
              v-model="chooseParmsDialogVisible"
              title="选择重点参数"
              width="600px"
              style="text-align: center"
            >
              <!-- {{ remainParmsTree }} -->
              <!-- 虚拟化树形控件 -->
              <el-input
                v-model="query"
                style="width: 240px"
                placeholder="请输入关键字"
                @input="onQueryChanged"
              />
              <el-tree-v2
                ref="remainParmsTreeRef"
                style="max-width: 600px"
                :data="remainParmsTree"
                :props="remainParmsTreeProps"
                :filter-method="filterMethod"
                show-checkbox
                :height="300"
              />
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="chooseParmsDialogVisible = false"
                    >取消</el-button
                  >
                  <el-button
                    type="primary"
                    @click="
                      chooseParmsDialogVisible = false;
                      addRemainParms();
                    "
                  >
                    确定
                  </el-button>
                </span>
              </template>
            </el-dialog>
          </div>
          <div class="removeParmsBtn">
            <el-button type="warning" plain @click="removeParmsConfirm()"
              >移除参数</el-button
            >
          </div>
        </div>
      </el-col>
      <!-- 中间--图形区 -->
      <el-col :span="14">
        <div
          :id="id"
          :class="className"
          :style="{ height, width }"
          :lazy="true"
        ></div>
      </el-col>
      <!-- 右侧--表单区 -->
      <el-col :span="6">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="遥测数据" prop="dataName">
            <el-input
              v-model="ruleForm.dataName"
              placeholder="遥测数据"
              readonly
            />
          </el-form-item>

          <el-form-item label="标记人员" prop="userName">
            <el-input v-model="ruleForm.userName" readonly />
          </el-form-item>

          <el-form-item label="标记时间段" required>
            <el-col :span="24">
              <el-form-item prop="beginTime">
                <el-input v-model="ruleForm.beginTime" readonly />
              </el-form-item>
            </el-col>
            <el-col class="text-center" :span="24">
              <span class="text-gray-500">-</span>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="endTime">
                <el-input v-model="ruleForm.endTime" readonly />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="事件名称" prop="errorName">
            <el-input
              v-model="ruleForm.errorName"
              placeholder="请填写事件名称"
            />
          </el-form-item>

          <el-form-item label="事件类型" prop="errorType">
            <el-select
              v-model="ruleForm.errorType"
              placeholder="请选择事件类型"
            >
              <el-option
                v-for="item in errorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
              <template #footer>
                <template v-if="!isAdding">
                  <el-button
                    text
                    type="primary"
                    bg
                    size="small"
                    @click="onAddOption"
                  >
                    添加事件类型
                  </el-button>
                  <el-button
                    text
                    type="danger"
                    bg
                    size="small"
                    @click="errorTypeDialogVisible = true"
                  >
                    删除事件类型
                  </el-button>
                </template>
                <template v-else>
                  <el-input
                    v-model="newErrorOption"
                    class="option-input"
                    placeholder="请输入事件类型"
                    size="small"
                  />
                  <el-button
                    type="primary"
                    size="small"
                    @click="addErrorType()"
                  >
                    确定
                  </el-button>
                  <el-button size="small" @click="clear">取消</el-button>
                </template>
              </template>
            </el-select>
          </el-form-item>

          <el-form-item label="事件描述" prop="errorDesc">
            <el-input
              v-model="ruleForm.errorDesc"
              type="textarea"
              placeholder="请详细描述事件"
            />
          </el-form-item>

          <el-form-item label="标注颜色" prop="markColor">
            <el-select
              v-model="ruleForm.markColor"
              placeholder="请选择标注颜色"
            >
              <el-option
                v-for="(option, index) in colorOptions"
                :key="option.value"
                :label="option.text"
                :value="option.value"
              >
                <el-tag :type="option.type">
                  {{ option.text }}
                </el-tag></el-option
              >
            </el-select>
          </el-form-item>

          <el-form-item>
            <!-- <el-button type="primary" @click="handleSubmit()"> 保存 </el-button> -->
            <el-button
              :type="currentErrorId === null ? 'primary' : 'success'"
              @click="
                currentErrorId === null
                  ? handleSubmit()
                  : updateErrorConfirm(currentErrorId)
              "
            >
              {{ currentErrorId === null ? "保存" : "修改" }}
            </el-button>
            <el-button
              type="danger"
              :disabled="!currentErrorId"
              @click="deleteErrorConfirm(currentErrorId)"
              >删除</el-button
            >
            <el-button type="info" @click="savePicture()">保存图片</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <div class="ReportArea" style="margin-top: 10px">
      <!-- 遥测数据/标注报表区域 -->
      <el-row>
        <el-col :span="18">
          <el-card
            class="telemetryDataReport"
            style="height: 800px; overflow: auto"
            shadow="never"
          >
            <template #header>
              <el-text tag="b">遥测数据报表</el-text>
            </template>
            <telemetryDataReport
              :errorData="chekedTaskErrorData"
              ref="telemetryDataReportRef"
            />
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card
            class="markReport"
            style="height: 800px; overflow: auto"
            shadow="never"
          >
            <template #header>
              <el-text tag="b">标注报表</el-text>
            </template>
            <markReport :errorData="chekedTaskErrorData" ref="markReportRef" />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
  <!-- 框选相关 -->
  <div v-if="selecting" class="selection-box" :style="selectionBoxStyle"></div>
  <!-- 显示当前任务的异常类型 -->
  <el-dialog
    v-model="errorTypeDialogVisible"
    title="异常类型"
    style="text-align: center"
  >
    <div class="taskErrorType">
      <el-table
        :data="TaskErrorTypeList"
        style="width: 100%"
        :header-cell-style="{
          background: 'rgb(236, 245, 255)',
          color: 'black',
        }"
      >
        <el-table-column property="typeId" label="类型ID">
          <template #default="scope">
            <el-tag>{{ scope.row.typeId }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="typeName" label="类型名" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              link
              :icon="Remove"
              type="primary"
              size="small"
              @click="removeErrorType(scope.row.typeId)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
  <!-- 上传离线CSV文件 -->
  <el-dialog
    v-model="uploadFileDialogVisible"
    title="离线文件上传"
    style="max-width: 25%; text-align: center"
  >
    <div class="taskErrorType">
      <el-form-item label="CSV文件上传:">
        <el-upload
          class="upload-demo"
          ref="uploadFileRef"
          action="#"
          :on-preview="handlePreview"
          :on-change="handleChange"
          :on-exceed="handleExceed"
          :limit="1"
          accept=".csv"
          :file-list="fileList"
          :auto-upload="false"
        >
          <template #trigger>
            <el-button type="primary" size="small">选择文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">
              只能上传csv文件。 限制一个文件，下一个文件会覆盖上一个文件。
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="uploadFileDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            uploadFileDialogVisible = false;
            uploadFile();
          "
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { FormInstance, FormRules } from "element-plus";
import { first } from "lodash";
import { Remove } from "@element-plus/icons-vue";
import axios from "axios";
import { useStore } from "vuex";
// import telemetryDataReport from "@/views/test-demo/faultAnalysis/telemetryDataReport.vue";
// import markReport from "@/views/test-demo/faultAnalysis/markReport.vue";
import { ElTreeV2 } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
// import type { TreeNode } from "element-plus/es/components/tree-v2/src/types";

const store = useStore();

/*
 *  
  标注跳转相关
 *
 */
// 监听 preFilterTableData 的变化
const scaleErrorId = ref<number | null>(null);
const scaleErrorData = ref<ErrorData | null>(null);
watch(
  () => store.state.isNotice,
  (newVal) => {
    debugger;
    console.log("监听成功");
    scaleErrorId.value = store.state.scaleErrorId;
    console.log("store.state.scaleErrorId", store.state.scaleErrorId);
    //提取scaleErrorId的信息
    scaleErrorData.value = TaskErrorDataArray.value.find(
      (item) => item.errorId === store.state.scaleErrorId
    );
    console.log("scaleErrorData.value", scaleErrorData.value);
    // 拉取对应曲线
    getJumpCheckedData();
  }
);

/*
 *  
  顶部-切换数据源、选择时间等
 *
 */
//切换数据源
const currentDataSource = ref("onLineDataSource");
const DataSourceOptions = ref([
  {
    value: "onLineDataSource",
    label: "在线",
  },
  {
    value: "offLineDataSource",
    label: "离线",
  },
]);

//选择时间
const TimeRange = ref(["", ""]);

//获取所有树节点--只要子节点
const allLeafParms = ref<string[]>([]); //存放所选子节点的数组

function getLeafNodes() {
  debugger;
  allLeafParms.value = [];

  if (FilterParmsTreeRef.value) {
    function traverse(node) {
      if (!node.children || node.children.length === 0) {
        allLeafParms.value.push(node.label);
      } else {
        node.children.forEach((child) => traverse(child));
      }
    }

    FilterParmsTree.value.forEach((node) => traverse(node));
  }
  console.log("allLeafParms:", allLeafParms.value);
}

function clearOptions() {
  debugger;
  //清空左侧已选项
  resetChecked();
  //清空中间图表
  getCheckedData();
  //清空右侧表单项
  resetForm(ruleFormRef.value);
  //清空选中标注
  currentErrorId.value = null;
}

//拉取在线数据
function getOnlineData() {
  preFilterData.value = [];
  getLeafNodes();

  const url = "/api/readDataByFreedom/";

  axios
    .post(url, {
      //TODO
      task_id: TASK_ID.value,
      beginTime: TimeRange.value[0],
      endTime: TimeRange.value[1],
      dataNames: allLeafParms.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.datas);
      preFilterData.value = res.data.datas;
      console.log("newpreFilterData", preFilterData.value);
      //更新遥测数据报表的值
      splitPreFilterData();
      //清空选项（左、中、右）
      clearOptions();
      ElMessage({
        message: "拉取数据成功！",
        type: "success",
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

/* 离线文件相关 */
const uploadFileDialogVisible = ref(false);

const fileList = ref<UploadUserFile[]>([]);

const fileUpload = ref();
const handleChange = (file: any, fileList) => {
  fileUpload.value = file;
};

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};
const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

//上传文件
function uploadFile() {
  debugger;
  const url = "/api/uplodData/";

  const formData = new FormData();
  const taskId_Str = TASK_ID.value.toString();
  formData.append("taskID", taskId_Str);
  formData.append("file", fileUpload.value.raw);
  //遍历打印formData里的值
  formData.forEach((value) => console.log(value));
  console.log(formData); // 获取要传给后端的标准结构数据
  console.log("提交表单");
  axios
    .post(url, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      ElMessage({
        message: "文件上传成功！",
        type: "success",
      });
      //更新下拉菜单
      getOfflineDataFiles();
    })
    .catch((error) => {
      console.error(error);
    });
}

//获取离线数据
function getOfflineData() {
  preFilterData.value = [];

  const url = "/api/readImportData/";

  axios
    .post(url, {
      //TODO
      taskID: TASK_ID.value,
      // taskID: 1,
      beginTime: csvTimeRange.value[0],
      endTime: csvTimeRange.value[1],
      fileName: checkedDataFile.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.data);
      preFilterData.value = res.data.data;
      console.log("newOffpreFilterData", preFilterData.value);
      //更新遥测数据报表的值
      splitPreFilterData();
      //清空选项（左、中、右）
      clearOptions();
      ElMessage({
        message: "读取数据成功！",
        type: "success",
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

//更新数据
//添加/移除遥测参数后更新对应遥测数据
function updateTaskData() {
  preFilterData.value = [];

  const url = "/api/readDataByTaskID/";

  axios
    .post(url, {
      taskID: TASK_ID.value,
      state: 0,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.data);
      preFilterData.value = res.data.data;
      console.log("updatepreFilterData", preFilterData.value);
      //更新遥测数据报表的值
      splitPreFilterData();
      //清空选项（左、中、右）
      clearOptions();
      ElMessage({
        message: "读取数据成功！",
        type: "success",
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

//更新遥测数据报表的值
const preFilterColumnList = ref<{ prop: string; label: string }[]>([]); //数据表头
const preFilterTableData = ref([]); //数据本体
function splitPreFilterData() {
  // 定义表头格式
  const columnHeaders = Object.keys(preFilterData.value[0]).map(
    (key, index) => ({
      prop: `prop${index}`,
      label: key,
    })
  );
  // 赋值给checkedFilteredColumnList
  preFilterColumnList.value = columnHeaders;
  console.log("preFilterColumnList.value", preFilterColumnList.value);
  // 在这里提交数据到 Vuex store
  store.commit("setpreFilterColumnList", preFilterColumnList.value);

  // 定义表格数据格式
  const parsedData = preFilterData.value.map((row) => {
    const rowData = {};
    Object.keys(row).forEach((key, index) => {
      rowData[`prop${index}`] = row[key];
    });
    return rowData;
  });
  // 赋值给preFilterTableData
  preFilterTableData.value = parsedData;
  console.log("preFilterTableData.value", preFilterTableData.value);
  // 在这里提交数据到 Vuex store
  store.commit("setpreFilterTableData", preFilterTableData.value);
}

//离线
// 监听 currentDataSource 的变化
watch(currentDataSource, (newValue) => {
  if (newValue === "offLineDataSource") {
    getOfflineDataFiles();
  }
});

const checkedDataFile = ref("");
const offLineDataFileOptions = ref([]);
//拉取数据
function getOfflineDataFiles() {
  offLineDataFileOptions.value = [];

  const url = "/api/selectImportData/";

  axios
    .post(url, {
      //TODO
      taskID: TASK_ID.value,
      // taskID: 1,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.fileName);
      offLineDataFileOptions.value = res.data.fileName.map((item) => ({
        key: item,
        label: item,
        value: item,
      }));
      console.log("offLineDataFileOptions", offLineDataFileOptions.value);
    })
    .catch((error) => {
      console.log(error);
    });
}

watch(checkedDataFile, (newValue) => {
  getCSVTimeRange();
});

//获取离线csv文件的起止时间
const csvBeginTime = ref<string | null>(null);
const csvEndTime = ref<string | null>(null);

//选择时间
const csvTimeRange = ref<[string | null, string | null]>([null, null]);

function getCSVTimeRange() {
  const url = "/api/selectTimeByTaskIdAndFileName/";

  axios
    .post(url, {
      //TODO
      taskID: TASK_ID.value,
      // beginTime: TimeRange.value[0],
      // endTime: TimeRange.value[1],
      fileName: checkedDataFile.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.data);
      csvBeginTime.value = res.data.beginTime;
      csvEndTime.value = res.data.endTime;
      console.log("csvBeginTime", csvBeginTime.value);
      console.log("csvEndTime", csvEndTime.value);
      csvTimeRange.value = [csvBeginTime.value, csvEndTime.value];
      ElMessage({
        message: "获取起止时间成功！",
        type: "success",
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

// const disabledDate = (time: Date) => {
//   debugger;
//   if (!csvBeginTime.value || !csvEndTime.value) {
//     return false;
//   }
//   const start = new Date(csvBeginTime.value).getTime();
//   const end = new Date(csvEndTime.value).getTime();
//   return time.getTime() < start || time.getTime() > end;
// };

/*
 *  
  左侧--参数区
 *
 */

/* 1.树状组件 */
// 定义树组件的 props
const defaultProps = {
  children: "children",
  label: "label",
};
// 定义树节点的类型
interface TreeNode {
  id: number;
  label: string;
  children?: TreeNode[];
}

const FilterParmsTreeRef = ref<InstanceType<typeof ElTree>>();

//搜索过滤
const filterText = ref("");
watch(filterText, (val) => {
  FilterParmsTreeRef.value!.filter(val);
});
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};

//处理节点选中状态变化的函数
const handleCheckChange = (
  node: any,
  checked: boolean,
  indeterminate: boolean
) => {
  console.log("Node checked:", node);
  console.log("Checked:", checked);
  console.log("Indeterminate:", indeterminate);
};

//清空树状选中项
const resetChecked = () => {
  FilterParmsTreeRef.value!.setCheckedKeys([], false);
};

//获取所选树节点--只要子节点
const checkedParms = ref<string[]>([]); //存放所选子节点的数组

//对应表单的"遥测数据"
const dataName = ref("");

const getCheckedChildNodes = () => {
  if (FilterParmsTreeRef.value) {
    const checkedNodes = FilterParmsTreeRef.value.getCheckedNodes();
    const childNodes = checkedNodes.filter(
      (node: TreeNode) => !node.children || node.children.length === 0
    );
    checkedParms.value = childNodes.map((node: TreeNode) => node.label);
    console.log("checkedParms:", checkedParms.value);
  }
};

/* 2.树状数据 */
const FilterParmsTree = ref<TreeNode[]>([]);

const TaskFilterParms = ref({}); //存放后端返回数据

//TODO
//任务ID
// const TASK_ID = ref<number>(200);
const TASK_ID = ref<number>(store.state.faultTaskId);

//读取预筛选参数
function readPreFilterParms() {
  TaskFilterParms.value = {};

  const url = "/api/readPreFilter/";

  axios
    .post(url, {
      //TODO
      taskId: TASK_ID.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      TaskFilterParms.value = res.data;
      console.log("TaskFilterParms", TaskFilterParms.value);
      //生成对应树状数据
      generateTreeData();
    })
    .catch((error) => {
      console.log(error);
    });
}

//解析左侧参数并展示
function generateTreeData() {
  debugger;
  FilterParmsTree.value = [];
  const categoryMap = new Map<string, TreeNode>();
  let idCounter = 1;

  for (const key in TaskFilterParms.value) {
    if (TaskFilterParms.value.hasOwnProperty(key)) {
      const item = TaskFilterParms.value[key];
      const { 所属分类, 所属系统 } = item;

      // 查找或创建分类节点
      let categoryNode = categoryMap.get(所属分类);
      if (!categoryNode) {
        categoryNode = {
          id: idCounter++,
          label: 所属分类,
          children: [],
        };
        categoryMap.set(所属分类, categoryNode);
        FilterParmsTree.value.push(categoryNode);
      }

      // 创建参数节点
      const paramNode: TreeNode = {
        id: idCounter++,
        label: key,
      };

      // 如果所属系统为空，则将节点添加到分类节点下
      if (!所属系统) {
        categoryNode.children!.push(paramNode);
      } else {
        // 查找或创建系统节点
        let systemNode = categoryNode.children!.find(
          (child) => child.label === 所属系统
        );
        if (!systemNode) {
          systemNode = {
            id: idCounter++,
            label: 所属系统,
            children: [],
          };
          categoryNode.children!.push(systemNode);
        }
        // 将参数节点添加到系统节点下
        systemNode.children!.push(paramNode);
      }

      //排序
      // 定义优先级数组
      const priorityOrder = [
        "重点参数",
        "报警单机遥测参数",
        "报警关联遥测参数",
        "其它遥测参数",
      ];

      // 根据优先级数组对 preFilterParms 进行排序
      FilterParmsTree.value.sort((a, b) => {
        const aIndex = priorityOrder.indexOf(a.label);
        const bIndex = priorityOrder.indexOf(b.label);

        // 如果分类不在优先级数组中，将其放在最后
        const aPriority = aIndex === -1 ? priorityOrder.length : aIndex;
        const bPriority = bIndex === -1 ? priorityOrder.length : bIndex;

        return aPriority - bPriority;
      });
    }
  }
  debugger;
}

/* 3.添加遥测参数 */
/* 3.1 树形控件 */
const chooseParmsDialogVisible = ref(false);

//剩余遥测参数
//后端返回--数组
const remainParms = ref<string[]>([]);
//转换后--树状结构
const remainParmsTree = ref<TreeNode[]>([]);

const remainParmsTreeRef = ref<InstanceType<typeof ElTreeV2>>();

const remainParmsTreeProps = {
  value: "id",
  label: "label",
  children: "children",
};

//查询
//搜索过滤
const query = ref("");
const onQueryChanged = (query: string) => {
  // TODO: fix typing when refactor tree-v2
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  remainParmsTreeRef.value!.filter(query);
};
const filterMethod = (query: string, node: TreeNode) => {
  return node.label!.includes(query);
};

//获取剩余非重点遥测参数
function getRemainParms() {
  const url = "/api/selectRemainDataName/";
  // const url = "/dev-api/api/v1/data/selectAllSate"; //MockUrl
  axios
    .post(url, {
      taskId: TASK_ID.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.remainDataNames);
      remainParms.value = res.data.remainDataNames;
      console.log(remainParms.value);
      convertTotransferFormat();
    })
    .catch((error) => {
      console.log(error);
    });
}

//转换为穿梭框的数据格式
function convertTotransferFormat() {
  debugger;
  const data = remainParms.value;
  const res = [];
  const map = {};

  data.forEach((item) => {
    if (item.trim() === "") return; // 跳过空字符串

    const prefix = item.match(/[A-Z]+/)[0]; // 提取前缀
    if (!map[prefix]) {
      const node = {
        id: prefix,
        label: prefix,
        children: [],
      };
      map[prefix] = node;
      console.log("node", node);
      res.push(node);
    }
    map[prefix].children.push({
      id: item,
      label: item,
    });
  });

  remainParmsTree.value = res;
  debugger;
  console.log("remainParmsTree.value", remainParmsTree.value);
}

//获取所选树节点--只要子节点
const checkedRemainParms = ref<string[]>([]); //存放所选子节点的数组

const getCheckedRemainNodes = () => {
  if (remainParmsTreeRef.value) {
    const checkedNodes = remainParmsTreeRef.value.getCheckedNodes();
    const childNodes = checkedNodes.filter(
      (node: TreeNode) => !node.children || node.children.length === 0
    );
    checkedRemainParms.value = childNodes.map((node: TreeNode) => node.label);
    console.log("checkedRemainParms:", checkedRemainParms.value);
  }
};

//添加选择的非重点遥测参数
function addRemainParms() {
  debugger;
  //首先获取所选叶子节点
  getCheckedRemainNodes();
  const url = "/api/addRemainDataName/";

  axios
    .post(url, {
      taskId: TASK_ID.value,
      dataNames: checkedRemainParms.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      //更新数据
      //读取预筛选参数
      readPreFilterParms();
      //读取更新后的预筛选数据
      updateTaskData();
    })
    .catch((error) => {
      console.log(error);
    });
}

//移除操作check
function removeParmsConfirm() {
  getCheckedChildNodes();
  if (checkedParms.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择要移除的参数！",
    });
    return;
  }
  ElMessageBox.confirm("将移除所选遥测参数，是否继续？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      debugger;
      removeRemainParms();
      // resetForm(ruleFormRef.value);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "操作取消！",
      });
    });
}

//移除选择的非重点遥测参数
function removeRemainParms() {
  const url = "/api/deleteRemainDataName/";

  axios
    .post(url, {
      taskId: TASK_ID.value,
      dataNames: checkedParms.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      //更新数据
      //清空所选数组
      checkedParms.value = [];
      //读取预筛选参数
      readPreFilterParms();
      //读取更新后的预筛选数据
      updateTaskData();
    })
    .catch((error) => {
      console.log(error);
    });
}

/*
 *  
  中间--图形区
 *
 */

/* 获取遥测数据 */
// 在组件中访问 Vuex store 中的数组
const markData = ref(store.state.preFilterTableData);
const markColumns = ref(store.state.preFilterColumnList);
const preFilterData = ref(store.state.preFilterData);

const checkedData = ref([]);

const checkedFilteredColumnList = ref<{ prop: string; label: string }[]>([]); //数据表头
const checkedFilteredTableData = ref<{}[]>([]); //数据本体

function getCheckedData() {
  debugger;
  getCheckedChildNodes();
  console.log("preFilterData.value", preFilterData.value);
  checkedData.value = preFilterData.value.map((item) => {
    return Object.keys(item).reduce((newItem, key) => {
      if (
        key === "时间" ||
        checkedParms.value.some((parm) => key.startsWith(parm))
      ) {
        newItem[key] = item[key];
      }
      return newItem;
    }, {});
  });
  //表格分离
  splitTableData();
}

function splitTableData() {
  console.log("splitTableData - start");
  // 定义表头格式
  const columnHeaders = Object.keys(checkedData.value[0]).map((key, index) => ({
    prop: `prop${index}`,
    label: key,
  }));
  // 赋值给checkedFilteredColumnList
  checkedFilteredColumnList.value = columnHeaders;
  // 定义表格数据格式
  const parsedData = checkedData.value.map((row) => {
    const rowData = {};
    Object.keys(row).forEach((key, index) => {
      rowData[`prop${index}`] = row[key];
    });
    return rowData;
  });
  // 赋值给checkedFilteredTableData
  checkedFilteredTableData.value = parsedData;
  //更新图表数据
  updateChartData();
  //更新标注信息
  getChekedTaskErrorData();
  console.log("splitTableData - end");
}

/*
 *  
  右侧--表单区
 *
 */

var dynamicswitchesData = ref<Array<{ value: boolean; text: string | number }>>(
  []
);

type DataRow = (string | number)[];

const saveButton = ref(0);

let globalFirstIndex = -1;
let globalSecondIndex = -1;
let globalMinIndexX = -1;
let globalMinIndexY = -1;
let globalMaxIndexX = -1;
let globalMaxIndexY = -1;
let intermediateTitle = "";

const selecting = ref(false);

let startX = 0;
let startY = 0;

const selectionBoxStyle = ref({
  left: "0px",
  top: "0px",
  width: "0px",
  height: "0px",
});

const handleMouseDown = (event: { pageX: number; pageY: number }) => {
  selecting.value = true;
  startX = event.pageX;
  startY = event.pageY;
};

const handleMouseMove = (event: { pageX: any; pageY: any }) => {
  if (selecting.value) {
    const currentX = event.pageX;
    const currentY = event.pageY;

    const width = Math.abs(currentX - startX) + "px";
    const height = Math.abs(currentY - startY) + "px";
    const left = Math.min(currentX, startX) + "px";
    const top = Math.min(currentY, startY) + "px";

    selectionBoxStyle.value = {
      width,
      height,
      left,
      top,
    };
  }
};

const handleMouseUp = () => {
  selecting.value = false;

  // 根据框选范围执行相应操作
};

/* 表单相关选项 */

//事件类型选项
const errorOptions = ref<{}[]>([]);
interface errorType {
  taskId: number;
  typeId: number;
  typeName: string;
}
const TaskErrorTypeList = ref<errorType[]>([]);

//获取当前任务的事件类型
function getTaskErrorOptions() {
  const url = "/api/selectErrorTypeByTaskId/";

  errorOptions.value = [];
  TaskErrorTypeList.value = [];

  axios
    .post(url, {
      taskId: TASK_ID.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      const errorTypes = res.data;
      console.log("errorTypes", errorTypes);
      //解析数据
      for (const key in errorTypes) {
        if (errorTypes.hasOwnProperty(key)) {
          errorOptions.value.push({
            value: errorTypes[key].type,
            label: errorTypes[key].type,
          });

          if (errorTypes[key].hasOwnProperty("taskid")) {
            TaskErrorTypeList.value.push({
              typeId: errorTypes[key].id,
              typeName: errorTypes[key].type,
              taskId: errorTypes[key].taskid,
            });
          }
        }
      }
      console.log("TaskErrorTypeList.value", TaskErrorTypeList.value);
    })
    .catch((error) => {
      console.log(error);
    });
}

//新增事件类型
const isAdding = ref(false);

const newErrorOption = ref("");

//添加errorType -- 当前Task
function addErrorType() {
  const url = "/api/addErrorTypeByTaskId/";

  axios
    .post(url, {
      taskId: TASK_ID.value,
      type: newErrorOption.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      ElMessage({
        message: res.data + "！",
        type: "success",
      });
      newErrorOption.value = "";
      //更新数据
      getTaskErrorOptions();
    })
    .catch((error) => {
      console.log(error);
    });
}

const onAddOption = () => {
  isAdding.value = true;
};
const clear = () => {
  newErrorOption.value = "";
  isAdding.value = false;
};

//删除errorType -- 当前Task
const errorTypeDialogVisible = ref(false);

function removeErrorType(typeId) {
  const url = "/api/deleteErrorTypeByTypeId/";

  axios
    .post(url, {
      typeId: typeId,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      ElMessage({
        message: res.data + "！",
        type: "success",
      });
      //更新数据
      getTaskErrorOptions();
    })
    .catch((error) => {
      console.log(error);
    });
}

// const errorOptions = [
//   {
//     value: "突发故障",
//     label: "突发故障",
//   },
//   {
//     value: "退化故障",
//     label: "退化故障",
//   },
//   {
//     value: "外部事件",
//     label: "外部事件",
//   },
//   {
//     value: "星上动作",
//     label: "星上动作",
//   },
//   {
//     value: "普通事件",
//     label: "普通事件",
//   },
// ];

//颜色选项
const colorOptions = [
  { text: "红色", type: "danger", value: "rgba(245,108,108,0.8)" },
  { text: "黄色", type: "warning", value: "rgba(231,166,68,0.8)" },
  { text: "蓝色", type: "primary", value: "rgba(96,174,255,0.8)" },
  { text: "绿色", type: "success", value: "rgba(112,197,69,0.8)" },
  { text: "灰色", type: "info", value: "rgba(144,147,153,0.8)" },
];

/* 用户相关选项 */
// 定义成员列表的类型
interface User {
  userId: number; //成员Id
  userName: string; //成员名
  authority: string; //权限
}
//成员列表
const TaskUserList = ref<User[]>([]);

//向后端查询成员列表
function queryTaskUser() {
  const url = "/api/selectUserIdByTaskId/";

  axios
    .post(url, {
      //TODO
      taskId: TASK_ID.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.datas);
      TaskUserList.value = res.data.datas.map((user) => ({
        userId: user.id,
        userName: user.username,
        authority: user.authority,
      }));
      console.log("TaskUserList.value", TaskUserList.value);
    })
    .catch((error) => {
      console.log(error);
    });
}

//获取当前用户名
function getCurrentUser() {
  const user_cookie = getCookie("user_cookie");
  const currentUserId = parseInt(user_cookie as string);

  const url = "/api/selectAllUser/";

  axios
    .post(url)
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      console.log(res.data.datas);
      const currentUser = res.data.datas.find(
        (user) => user.id === currentUserId
      );
      ruleForm.userName = currentUser.username;
      console.log("ruleForm.userName", ruleForm.userName);
    })
    .catch((error) => {
      console.log(error);
    });
}

//获取当前用户id--cookie
function getCookie(name: string): string | null {
  const nameEQ = name + "=";
  const cookies = document.cookie.split(";");

  for (let i = 0; i < cookies.length; i++) {
    let cookie = cookies[i].trim();
    if (cookie.indexOf(nameEQ) == 0) {
      return cookie.substring(nameEQ.length, cookie.length);
    }
  }
  return null;
}
/* 报表导出相关 */

//保存echart并发给后端
function savePicture() {
  debugger;
  const url = "/api/uploadImage/";

  //获取echarts图表的base64地址
  var baseImage = chart.value.getDataURL({
    type: "png",
    pixelRatio: 1.5, //放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
    backgroundColor: "#fff",
  }); //获取到的是一串base64信息
  // 将 Blob 对象包装成 FormData
  const formData = new FormData();
  const blobData = base64ToBlob(baseImage);
  //图片命名不重复（taskid+时间戳）
  const timestamp = new Date().getTime();
  const picName = "任务" + TASK_ID.value + "-" + timestamp;
  formData.append("file", blobData, picName + ".png");
  const parmsToSend = ref({});
  parmsToSend.value = {
    taskId: TASK_ID.value,
  };

  formData.append("parameter", JSON.stringify(parmsToSend.value));
  debugger;

  axios
    .post(url, formData)
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      ElMessage({
        message: "图片保存成功！",
        type: "success",
      });
    })
    .catch((error) => {
      console.log(error);
    });
}

// function savePicture() {
//   debugger;
//   //获取echarts图表的base64地址
//   var baseImage = chart.value.getDataURL({
//     type: "png",
//     pixelRatio: 1.5, //放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
//     backgroundColor: "#fff",
//   }); //获取到的是一串base64信息
//   // 将 Blob 对象包装成 FormData
//   const formData = new FormData();
//   const blobData = base64ToBlob(baseImage);
//   //图片命名不重复（taskid+时间戳）
//   const timestamp = new Date().getTime();
//   const picName = "任务" + TASK_ID.value + "-" + timestamp;
//   formData.append("chartImage", blobData, picName + ".png");
//   const elink = document.createElement("a");
//   elink.download = picName;
//   elink.style.display = "none";
//   elink.href = baseImage;
//   document.body.appendChild(elink);
//   elink.click();
//   URL.revokeObjectURL(elink.href); // 释放URL 对象
//   document.body.removeChild(elink);
// }

// 将 base64 数据转换为 Blob 对象
function base64ToBlob(base64Data, contentType = "image/png") {
  const byteCharacters = atob(base64Data.split(",")[1]);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: contentType });
}

/* 异常标注相关 */
/*
 * 后端返回的异常标注信息
 *
 */

// 定义异常标注的类型
interface ErrorData {
  dataName: string[]; //遥测数据
  errorName: string; //事件名称
  errorType: string; //事件类型
  errorDesc: string; //事件描述

  beginTime: string; //开始时间
  endTime: string; //结束时间
  maxValue: string; //最大值
  minValue: string; //最小值

  userId: number; //标注人Id

  //唯二新增
  errorId: number; //标注人Id
  userName: string; //标注人--唯一新增

  Lev: number; //异常标注等级
  father: number; //标注父类
  markColor: string; //异常颜色

  channel_code: number; //卫星通道
  unique_code: string; //卫星唯一id
  state: number; //审批状态
}

//当前任务下所有异常标注数据
const TaskErrorData = ref({});

//当前任务下所有异常标注数据--数组格式
const TaskErrorDataArray = ref<ErrorData[]>([]);

// 选中的dataNameArray
// const checkedDataNameArray = ref<string[]>([]);

// //选中成员的异常标注数据
const chekedTaskErrorData = ref<ErrorData[]>([]);

//获取所选参数相关的ErrorData
function getChekedTaskErrorData() {
  console.log("getCheckedTaskErrorData");
  chekedTaskErrorData.value = TaskErrorDataArray.value.filter((item) => {
    return item.dataName.every((dataName) =>
      checkedParms.value.some((parm) => dataName.includes(parm))
    );
  });
  console.log("chekedTaskErrorData", chekedTaskErrorData.value);
  getMarkAreaData();
}

// 监听 chekedTaskErrorData 的变化
watch(TaskErrorDataArray, () => {
  getChekedTaskErrorData();
});

// 定义标注对象的类型
interface MarkPointData {
  dataName: string[]; //遥测数据
  userName: string; //标注人
  userId: number; //标注人Id
  beginTime: string; //开始时间
  endTime: string; //结束时间
  maxValue: string; //最大值
  minValue: string; //最小值
  errorName: string; //事件名称
  errorType: string; //事件类型
  errorDesc: string; //事件描述
  markColor: string; //标注颜色
  Lev: number; //异常标注等级
  errorId: number; //异常Id
  father: number; //标注父类
}

//解析数据--只保留标注所需信息
const markAreaDataArray = ref<MarkPointData[]>([]);

//只保留标注所需数据
function getMarkAreaData() {
  console.log("getMarkAreaData");
  markAreaDataArray.value = chekedTaskErrorData.value.map((error) => ({
    dataName: error.dataName,
    userName: error.userName,
    userId: error.userId,
    beginTime: error.beginTime,
    endTime: error.endTime,
    maxValue: error.maxValue,
    minValue: error.minValue,
    errorName: error.errorName,
    errorType: error.errorType,
    errorDesc: error.errorDesc,
    markColor: error.markColor,
    Lev: error.Lev,
    father: error.father,
    errorId: error.errorId,
  }));

  console.log("markAreaDataArray", markAreaDataArray.value);
  if (chart.value) {
    parseMarkArea();
  }
}

//向后端查询成员标注
function queryTaskErrorData() {
  const url = "/api/readErrorDataByTaskID/";
  TaskErrorData.value = {};

  axios
    .post(url, {
      //TODO
      task_id: TASK_ID.value,
      state: 1,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      TaskErrorData.value = res.data;
      console.log("TaskErrorData", TaskErrorData);
      // 生成标注对象数组
      convertErrorDataToArr();
    })
    .catch((error) => {
      console.log(error);
    });
}

// 获取用户名称
const getUserName = (userId: number): string => {
  const user = TaskUserList.value.find((user) => user.userId === userId);
  return user ? user.userName : "NULL";
};

//转为数组格式
function convertErrorDataToArr() {
  debugger;
  TaskErrorDataArray.value = [];

  TaskErrorDataArray.value = Object.keys(TaskErrorData.value).map((key) => {
    const error = TaskErrorData.value[key];
    return {
      dataName: error.dataName,
      userName: getUserName(error.userId),
      userId: error.userId,

      beginTime: error.begintime,
      endTime: error.endtime,
      maxValue: error.maxValue,
      minValue: error.minValue,

      errorName: error.errorname || error.errorName,
      errorType: error.type,
      errorDesc: error.description,
      markColor: error.color,

      Lev: error.Lev,
      father: error.father,
      errorId: parseInt(key), // 将键解析为整数并作为 errorId

      channel_code: parseInt(error.channel_code), //卫星通道
      unique_code: error.unique_code, //卫星唯一id
      state: parseInt(error.state), //审批状态
    };
  });

  console.log("TaskErrorDataArray", TaskErrorDataArray.value);

  getMarkAreaData();
}

/*
 * 前端展示的异常标注信息
 *
 */
// 定义 markAreaData 的类型
/*
  标注区域的信息
  1.包含 name、xAxis、yAxis 和 itemStyle 属性的对象
  2.只包含 xAxis 和 yAxis 属性的对象
*/
type MarkAreaDataItem =
  | {
      name: string;
      xAxis: string | number;
      yAxis: string;
      itemStyle: { color: string };
      userId: number;
      dataName: string;
      userName: string;
      beginTime: string;
      endTime: string;
      errorName: string;
      errorType: string;
      errorDesc: string;
      markColor: string;
      errorId: number;
    }
  | { xAxis: string | number; yAxis: string; name?: undefined };

// 创建 ref 对象并初始化
const markAreaData = ref<MarkAreaDataItem[][]>([]);

//定义markAreaData的长的范围maxValue、minValue
const maxValue = ref<string>("");
const minValue = ref<string>("");
//markAreaData的宽的范围:beginTime、endTime

//解析标注
function parseMarkArea() {
  debugger;
  markAreaData.value = [];

  markAreaDataArray.value.forEach((markArea) => {
    markAreaData.value.push([
      {
        name: markArea.errorName,
        xAxis: markArea.beginTime,
        yAxis: markArea.minValue,
        itemStyle: { color: markArea.markColor },
        dataName: markArea.dataName,
        userName: markArea.userName,
        beginTime: markArea.beginTime,
        endTime: markArea.endTime,
        errorName: markArea.errorName,
        errorType: markArea.errorType,
        errorDesc: markArea.errorDesc,
        markColor: markArea.markColor,
        errorId: markArea.errorId,
      },
      {
        xAxis: markArea.endTime,
        yAxis: markArea.maxValue,
      },
    ]);
  });

  console.log("markAreaData", markAreaData.value);

  chart.value?.setOption({
    series: [
      {
        markArea: {
          data: markAreaData.value,
        },
      },
    ],
  });
}

const handleClick = () => {
  // 修改 saveButton 的值为 1
  saveButton.value = 1;
};

// 将 saveButton 和 handleClick 方法暴露给模板
const myChart = ref<echarts.ECharts | null>(null);
const selectedData = ref<number[]>([]);

//TODO
//卫星相关
const CHANNEL_CODE = ref<number | null>(12);
const UNIQUE_CODE = ref<string | null>("KABCA");

//默认标注颜色
const DEFAULT_MARK_COLOR = ref("rgba(245,108,108,0.8)");

/*右侧--表单相关*/
interface RuleForm {
  dataName: string;
  userName: string;

  beginTime: string;
  endTime: string;

  errorName: string;
  errorType: string;
  errorDesc: string;

  markColor: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  dataName: "",
  userName: "",

  beginTime: "",
  endTime: "",

  errorName: "",
  errorType: "",
  errorDesc: "",

  markColor: DEFAULT_MARK_COLOR.value,
});

const rules = reactive<FormRules<RuleForm>>({
  dataName: [
    { required: true, message: "遥测数据不能为空", trigger: "change" },
  ],
  beginTime: [
    {
      required: true,
      message: "请选择起始时间",
      trigger: "change",
    },
  ],
  endTime: [
    {
      required: true,
      message: "请选择结束时间",
      trigger: "change",
    },
  ],
  errorName: [
    {
      required: true,
      message: "事件名称不能为空",
      trigger: "change",
    },
  ],
  errorType: [{ required: true, message: "请选择事件类型", trigger: "blur" }],
  errorDesc: [{ required: true, message: "请填写事件描述", trigger: "blur" }],
  markColor: [{ required: true, message: "请选择标注颜色", trigger: "blur" }],
});

const dynamicSaveArray: RuleForm[] = [];

//表单校验
const handleSubmit = () => {
  debugger;
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      // 表单校验通过，执行提交操作
      submitForm();
      resetForm(ruleFormRef.value);
    } else {
      // 表单校验不通过，处理错误信息或其他操作
      console.log("表单校验不通过");
    }
  });
};

//提交表单--插入标注byTaskId
function submitForm() {
  const url = "/api/insertErrorDataByTaskID/";
  const strArray = ruleForm.dataName.split(", ");

  // const formData = savePicture();
  // const parmsToSend = ref({});
  // parmsToSend.value = {
  //   dataName: strArray,
  //   beginTime: ruleForm.beginTime,
  //   endTime: ruleForm.endTime,
  //   errorName: ruleForm.errorName,
  //   type: ruleForm.errorType,
  //   description: ruleForm.errorDesc,
  //   // userId: currentUserId.value,
  //   color: ruleForm.markColor,

  //   maxValue: maxValue.value,
  //   minValue: minValue.value,

  //   //TODO
  //   unique_code: UNIQUE_CODE.value,
  //   channel_code: CHANNEL_CODE.value,
  //   taskId: TASK_ID.value,
  // };
  // formData.append("parameter", JSON.stringify(parmsToSend.value));

  debugger;
  axios
    .post(url, {
      dataName: strArray,
      beginTime: ruleForm.beginTime,
      endTime: ruleForm.endTime,
      errorName: ruleForm.errorName,
      type: ruleForm.errorType,
      description: ruleForm.errorDesc,
      // userId: currentUserId.value,
      color: ruleForm.markColor,

      maxValue: maxValue.value,
      minValue: minValue.value,

      //TODO
      unique_code: UNIQUE_CODE.value,
      channel_code: CHANNEL_CODE.value,
      taskId: TASK_ID.value,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      ElMessage({
        message: "插入成功！",
        type: "success",
      });
      //插入后更新数据
      queryTaskErrorData();
      //更新标注
    })
    .catch((error) => {
      console.log(error);
    });
}
// function submitForm() {
//   const url = "/api/insertErrorDataByTaskID/";
//   const strArray = ruleForm.dataName.split(", ");

//   debugger;
//   axios
//     .post(url, {
//       dataName: strArray,
//       beginTime: ruleForm.beginTime,
//       endTime: ruleForm.endTime,
//       errorName: ruleForm.errorName,
//       type: ruleForm.errorType,
//       description: ruleForm.errorDesc,
//       // userId: currentUserId.value,
//       color: ruleForm.markColor,

//       maxValue: maxValue.value,
//       minValue: minValue.value,

//       //TODO
//       unique_code: UNIQUE_CODE.value,
//       channel_code: CHANNEL_CODE.value,
//       taskId: TASK_ID.value,
//     })
//     .then((res) => {
//       debugger;
//       console.log(res);
//       console.log(res.data);
//       ElMessage({
//         message: "插入成功！",
//         type: "success",
//       });
//       //插入后更新数据
//       queryTaskErrorData();
//       //更新标注
//     })
//     .catch((error) => {
//       console.log(error);
//     });
// }

//点击获取当前ErrorId
const currentErrorId = ref<number | null>(null);

/*
 * 更新标注
 */
//更新标注byErrorId
function updateErrorData(errorId) {
  console.log("更新标注ID:", errorId);
  const url = "/api/updateErrorDataByErrorId/";

  debugger;
  axios
    .post(url, {
      errorId: currentErrorId.value,
      errorName: ruleForm.errorName,
      type: ruleForm.errorType,
      description: ruleForm.errorDesc,
      color: ruleForm.markColor,
      beginTime: ruleForm.beginTime,
      endTime: ruleForm.endTime,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      ElMessage({
        message: "更新成功！",
        type: "success",
      });
      //更新后更新数据
      queryTaskErrorData();
      currentErrorId.value = null;
    })
    .catch((error) => {
      console.log(error);
    });
}

//更新操作check
function updateErrorConfirm(errorId) {
  ElMessageBox.confirm(
    "将更新异常ID为" + errorId + "的标注数据，是否继续？",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      debugger;
      updateErrorData(errorId);
      resetForm(ruleFormRef.value);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消更新",
      });
    });
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  //清空表单
  if (!formEl) return;
  const dataName = ruleForm.dataName;
  const userName = ruleForm.userName;
  formEl.resetFields();
  ruleForm.dataName = dataName;
  ruleForm.userName = userName;
  //清空finalIndex的值
  finalIndex.firstIndex = null;
  finalIndex.secondIndex = null;
  finalIndex.minIndexx = null;
  finalIndex.minIndexy = null;
  finalIndex.maxIndexx = null;
  finalIndex.maxIndexy = null;
  console.log(finalIndex);
};

/*
 * 删除标注
 */
//执行删除操作
function deleteErrorDataByErrorId(errorId) {
  console.log("删除标注ID:", errorId);
  const url = "/api/deleteErrorDataByErrorID/";

  axios
    .post(url, {
      errorID: errorId,
    })
    .then((res) => {
      debugger;
      console.log(res);
      console.log(res.data);
      ElMessage({
        message: res.data,
      });
      //删除后更新数据、清空表单及所选errorId
      queryTaskErrorData();
      currentErrorId.value = null;
    })
    .catch((error) => {
      console.log(error);
    });
}

//删除操作check
function deleteErrorConfirm(errorId) {
  ElMessageBox.confirm(
    "异常ID为" + errorId + "的标注将被删除，是否继续？",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      deleteErrorDataByErrorId(errorId);
      resetForm(ruleFormRef.value);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
}

defineExpose({
  queryTaskErrorData,
  resizeChart,
});

const dynamicsource = ref<Array<string | number>>([]);

const dynamicArray = ref<string[][]>([]);

// const sourcetitle = ref(
//   checkedFilteredColumnList.value.map((item) => item.label)
// );
const sourcetitle = computed(() =>
  checkedFilteredColumnList.value.map((item) => item.label)
);

// const sourcetitle = ref([
//   "Day",
//   "Email",
//   "Union Ads",
//   "Video Ads",
//   "Direct",
//   "Search Engine",
// ]);

// 生成目标格式的二维数组
// 转换为所需的格式
const datasetSource = ref([]);

// 定义 source_copy 为 ref
const source_copy = ref<DataRow[]>([]);

// const source_copy = ref<DataRow[]>([
//   // ['Day', 'Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine'],
//   ["Mon", 120, 220, 150, 320, 820],
//   ["Tue", 132, 182, 232, 332, 932],
//   ["Wed", 101, 191, 201, 301, 901],
//   ["Thu", 134, 234, 154, 334, 934],
//   ["Fri", 90, 290, 190, 390, 1290],
//   ["Sat", 210, 310, 410, 320, 1320],
//   ["MoMon", 230, 200, 400, 290, 1430],
//   ["TueTue", 270, 150, 370, 260, 1490],
//   ["WedWed", 240, 170, 320, 280, 1450],
//   ["ThuThe", 235, 190, 300, 290, 1400],
//   ["FriFri", 233, 150, 250, 230, 1380],
//   ["SatSat", 210, 100, 330, 250, 1300],
// ]);
const source_second = ref<DataRow[]>([
  // ['Day', 'Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine'],
  ["Mon", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["Tue", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["Wed", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["Thu", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["Fri", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["Sat", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["MoMon", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["TueTue", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["WedWed", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["ThuThe", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["FriFri", -0.2, -0.2, -0.2, -0.2, -0.2],
  ["SatSat", -0.2, -0.2, -0.2, -0.2, -0.2],
]);
interface FinalIndex {
  firstIndex: number | null;
  secondIndex: number | null;
  minIndexx: number | null;
  minIndexy: number | null;
  maxIndexx: number | null;
  maxIndexy: number | null;
}
let finalIndex: FinalIndex = {
  firstIndex: null,
  secondIndex: null,
  minIndexx: null,
  minIndexy: null,
  maxIndexx: null,
  maxIndexy: null,
};

// function normalizeDatamethod(data: DataRow[], startCol = 1): DataRow[] {
//   if (!data || data.length === 0) {
//     return [];
//   }

//   const numCols = data[0].length;

//   // 提取数值部分
//   const values = data.map((row) =>
//     row.slice(startCol).map((val) => Number(val))
//   );

//   // 计算每列的最小值和最大值
//   const minVals = values[0].map((_, colIdx) =>
//     Math.min(...values.map((row) => row[colIdx]))
//   );
//   const maxVals = values[0].map((_, colIdx) =>
//     Math.max(...values.map((row) => row[colIdx]))
//   );

//   // 归一化数值部分
//   const normalizedValues = values.map((row) =>
//     row.map((val, colIdx) => {
//       const min = minVals[colIdx];
//       const max = maxVals[colIdx];
//       return (val - min) / (max - min);
//     })
//   );

//   // 重新组合归一化后的数据
//   const normalizedData = data.map((row, rowIdx) => [
//     ...row.slice(0, startCol),
//     ...normalizedValues[rowIdx],
//   ]);

//   return normalizedData;
// }
function normalizeDatamethod(data: DataRow[], startCol = 1): DataRow[] {
  if (!data || data.length === 0) {
    return [];
  }

  const numCols = data[0].length;

  // 提取数值部分，并将非数值(NaN)跳过
  const values = data.map((row) =>
    row.slice(startCol).map((val) => Number(val))
  );

  // 计算每列的最小值，跳过 NaN
  const minVals = values[0].map((_, colIdx) =>
    Math.min(...values.map((row) => row[colIdx]).filter((val) => !isNaN(val)))
  );
  console.log("minVals", minVals);

  // 计算每列的最大值，跳过 NaN
  const maxVals = values[0].map((_, colIdx) =>
    Math.max(...values.map((row) => row[colIdx]).filter((val) => !isNaN(val)))
  );
  console.log("maxVals", maxVals);

  // 归一化数值部分，跳过 NaN
  const normalizedValues = values.map((row) =>
    row.map((val, colIdx) => {
      const min = minVals[colIdx];
      const max = maxVals[colIdx];
      if (isNaN(val)) {
        return NaN; // 保留 NaN
      }
      if (max === min) {
        return 1; // 如果最大值和最小值相等，设定归一化值为 1
      }
      return (val - min) / (max - min);
    })
  );

  // 重新组合归一化后的数据
  const normalizedData = data.map((row, rowIdx) => [
    ...row.slice(0, startCol),
    ...normalizedValues[rowIdx],
  ]);

  return normalizedData;
}

// 进行归一化处理，从第三列开始
// const normalizedData = normalizeDatamethod(source_copy.value);
const normalizedData = ref<DataRow[]>([]);

//更新图表数据
function updateChartData() {
  console.log("updateChartData");
  datasetSource.value = [];
  source_copy.value = [];
  normalizedData.value = [];
  visualseries.value = [];
  availableindex.value = [];
  ruleForm.dataName = "";
  //更新datasource
  debugger;
  datasetSource.value = checkedFilteredTableData.value.map((item) => {
    // 将对象的所有属性值组成数组
    const values = Object.keys(item).map((key, index) => {
      // 将第一列以外的数据转换为数字类型
      if (index !== 0) {
        return parseFloat(item[key]);
        // 如果要转换为整数类型，可以使用 parseInt(item[key], 10)
      }
      return item[key]; // 第一列保持原样
    });
    return values;
  });
  console.log("datasetSource.value", datasetSource.value);
  //更新source_copy
  source_copy.value = datasetSource.value;
  debugger;
  // 进行归一化处理，从第三列开始
  normalizedData.value = normalizeDatamethod(source_copy.value);
  console.log("normalizedData.value", normalizedData.value);
  //根据sourcetitle长度设置line的条数
  for (let typeIndex = 1; typeIndex < sourcetitle.value.length; typeIndex++) {
    visualseries.value.push({
      type: "line",
    });
  }
  for (let ableindex = 1; ableindex < sourcetitle.value.length; ableindex++) {
    availableindex.value.push(ableindex);
  }
  const displaytype: any[] = [];
  for (let i = 0; i < availableindex.value.length; i += 1) {
    displaytype.push(sourcetitle.value[availableindex.value[i]]);
    // debugger
  }
  const displaydatatype = displaytype.join(", ");
  ruleForm.dataName = displaydatatype;
  console.log("displaytype", displaytype);
  console.log("ruleForm.dataName", ruleForm.dataName);

  const options = {
    dataset: {
      source: normalizedData.value,
    },
    series: visualseries.value.map((_, index) => ({
      type: "line",
      encode: {
        x: 0,
        y: 1 + index, // 使用不同的 y 列
      },
    })),
  };
  chart.value.setOption(options);
}

//获取跳转标注相关数据
function getJumpCheckedData() {
  console.log("getJumpCheckedData - start");
  debugger;
  // //提取scaleErrorId的信息
  // scaleErrorData.value = TaskErrorDataArray.value.find(
  //   (item) => item.errorId === store.state.scaleErrorId
  // );
  // console.log("scaleErrorData.value", scaleErrorData.value);
  if (!scaleErrorData.value) {
    return;
  }
  checkedParms.value = scaleErrorData.value.dataName;
  // console.log("dataNames", dataNames);
  // checkedParms
  console.log("preFilterData.value", preFilterData.value);
  checkedData.value = preFilterData.value.map((item) => {
    return Object.keys(item).reduce((newItem, key) => {
      if (
        key === "时间" ||
        checkedParms.value.some((parm) => key.startsWith(parm))
      ) {
        newItem[key] = item[key];
      }
      return newItem;
    }, {});
  });
  //表格分离
  splitTableData();
  //缩放时间轴
  scaleTimeLine();
  //还原对应标注的信息
  ruleForm.dataName = scaleErrorData.value.dataName.join(", ");
  ruleForm.userName = scaleErrorData.value.userName;
  ruleForm.beginTime = scaleErrorData.value.beginTime;
  ruleForm.endTime = scaleErrorData.value.endTime;
  ruleForm.errorName = scaleErrorData.value.errorName;
  ruleForm.errorType = scaleErrorData.value.errorType;
  ruleForm.errorDesc = scaleErrorData.value.errorDesc;
  ruleForm.markColor = scaleErrorData.value.markColor;
  currentErrorId.value = scaleErrorData.value.errorId;
  debugger;
  console.log("getJumpCheckedData - end");
}

function scaleTimeLine() {
  console.log("scaleTimeLine");
  //获取跳转标注的beginTime和endTime
  if (!scaleErrorData.value) {
    return;
  }

  const beginTime = scaleErrorData.value.beginTime;
  const endTime = scaleErrorData.value.endTime;

  chart.value?.setOption({
    dataZoom: [
      {
        type: "slider",
        xAxisIndex: 0,
        filterMode: "none",
        // start: 80,
        startValue: beginTime,
        endValue: endTime,
        // startValue: "2022-08-26 15:34:46",
        // endValue: "2022-08-26 17:55:34",
      },
      {
        type: "inside",
        xAxisIndex: 0,
        filterMode: "none",
        // start: 80,
        startValue: beginTime,
        endValue: endTime,
        // startValue: "2022-08-26 15:34:46",
        // endValue: "2022-08-26 17:55:34",
      },
    ],
  });
}

for (
  let switchdataIndex = 1;
  switchdataIndex < sourcetitle.value.length;
  switchdataIndex++
) {
  // 确保使用正确的索引来获取单个元素
  const textValue = sourcetitle.value[switchdataIndex]; // 假设索引为 0
  dynamicswitchesData.value.push({
    value: false,
    text: textValue,
  });
}
// }
const availableindex = ref<number[]>([]);
dynamicArray.value.push(source_copy.value.map((row) => String(row[0])));

const visualseries = ref<{ type: string }[]>([]);

// for (let typeIndex = 1; typeIndex < sourcetitle.value.length; typeIndex++) {
//   visualseries.push({
//     type: "line",
//   });
// }
// for (let ableindex = 1; ableindex < sourcetitle.value.length; ableindex++) {
//   availableindex.value.push(ableindex);
// }

// debugger
const props = defineProps({
  id: {
    type: String,
    default: "WorkTableChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});

const option = {
  dataset: {
    source: normalizedData.value,
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
    },
  },
  grid: {
    left: "3%",
    right: "4%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
  },
  yAxis: {
    type: "value",
    min: -0.2,
    max: 1.2,
    interval: 0.2,
  },
  toolbox: {
    feature: {
      dataZoom: {
        yAxisIndex: false,
      },
      brush: {
        type: ["lineX", "clear", "keep"],
      },
    },
  },
  brush: {
    xAxisIndex: "all",
    brushLink: "all",
    outOfBrush: {
      colorAlpha: 0.1,
    },
    brushStyle: {
      borderWidth: 1,
      color: "#ff0000",
      borderColor: "#ff0000",
      opacity: 0.3,
    },
  },
  dataZoom: [
    {
      type: "slider",
      xAxisIndex: 0,
      filterMode: "none",
    },
    {
      type: "inside",
      xAxisIndex: 0,
      filterMode: "none",
    },
  ],
  series: visualseries.value.map((_, index) => ({
    type: "line",
    encode: {
      x: 0,
      y: 1 + index, // 使用不同的 y 列
    },
  })),
};

const chart = ref<any>("");

function resizeChart() {
  chart.value.resize();
}

onMounted(() => {
  //获取当前用户名
  getCurrentUser();
  //查询任务所含成员
  queryTaskUser();
  //获取当前用户名并写入表单
  getCurrentUser();
  //获取当前任务errorType
  getTaskErrorOptions();
  //读取预筛选参数
  readPreFilterParms();
  //查询当前任务异常数据
  queryTaskErrorData();

  // 图表初始化
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );
  chart.value.setOption(option);

  // 大小自适应
  window.addEventListener("resize", () => {
    chart.value.resize();
  });

  // chart.value.setOption(option);
  chart.value.on("brushSelected", function (params: { batch: any[] }) {
    //重置表单和currentErrorId
    resetForm(ruleFormRef.value);
    currentErrorId.value = null;
    //更新标注人--因为可能会有点击已有标注后再框选的情况--已有标注人和框选的user不一定一样，所以需要更新
    getCurrentUser();
    //更新遥测数据dataName--因为可能会有点击已有标注后再框选的情况--已有标注和框选的dataName不一定一样，所以需要更新
    const displaytype: any[] = [];
    for (let i = 0; i < availableindex.value.length; i += 1) {
      displaytype.push(sourcetitle.value[availableindex.value[i]]);
      // debugger
    }
    const displaydatatype = displaytype.join(", ");
    ruleForm.dataName = displaydatatype;
    console.log("displaytype", displaytype);
    console.log("ruleForm.dataName", ruleForm.dataName);

    if (
      params.batch &&
      params.batch[0] &&
      params.batch[0].areas &&
      params.batch[0].areas[0]
    ) {
      //原始代码
      var brushComponent = params.batch[0];

      var area = brushComponent.areas[0];

      // 提取 coordRange
      var coord = area.coordRange;
      console.log("Coord Range:", coord[0]);
      let firstIndex = 0,
        secondIndex = 0;
      if (coord[0] > coord[1]) {
        firstIndex = coord[1];
        secondIndex = coord[0];
      } else if (coord[0] < coord[1]) {
        firstIndex = coord[0];
        secondIndex = coord[1];
      }
      console.log(firstIndex);
      console.log(secondIndex);

      let maxIndexx = secondIndex;
      let maxIndexy = availableindex.value[0];
      let minIndexx = firstIndex;
      let minIndexy = availableindex.value[0];
      // debugger
      for (
        let interindex = firstIndex;
        interindex < secondIndex + 1;
        interindex += 1
      ) {
        for (
          let interinterindex = 0;
          interinterindex < availableindex.value.length;
          interinterindex += 1
        ) {
          let useindex = availableindex.value[interinterindex];

          //  debugger
          if (
            normalizedData.value[interindex][useindex] <
            normalizedData.value[minIndexx][minIndexy]
          ) {
            //  debugger
            minIndexx = interindex;
            minIndexy = useindex;
          }
          if (
            normalizedData.value[interindex][useindex] >
            normalizedData.value[maxIndexx][maxIndexy]
          ) {
            // debugger
            maxIndexx = interindex;
            maxIndexy = useindex;
          }
        }
      }
      // debugger
      ruleForm.beginTime = String(normalizedData.value[firstIndex][0]);
      ruleForm.endTime = String(normalizedData.value[secondIndex][0]);
      finalIndex.firstIndex = firstIndex;
      finalIndex.secondIndex = secondIndex;
      finalIndex.minIndexx = minIndexx;
      finalIndex.minIndexy = minIndexy;
      finalIndex.maxIndexx = maxIndexx;
      finalIndex.maxIndexy = maxIndexy;
      console.log("finalIndex", finalIndex);
      console.log("minIndexx", minIndexx);
      console.log(typeof minIndexx);
      console.log("minIndexy", minIndexy);
      console.log("normalizedData.value", normalizedData.value);
      console.log(normalizedData.value[minIndexx][minIndexy]);
      console.log(normalizedData.value[maxIndexx][maxIndexy]);
      //定义markAreaData的长的范围maxValue、minValue
      minValue.value = normalizedData.value[minIndexx][minIndexy].toString();
      maxValue.value = normalizedData.value[maxIndexx][maxIndexy].toString();
      console.log("maxValue.value", maxValue.value);
      console.log("minValue.value", minValue.value);
    }

    const isInGrid = (pointInPixel: number[]): boolean => {
      return chart.value.containPixel("grid", pointInPixel);
    };
  });
  //配置tooltip相关信息
  if (chart.value) {
    const options = {
      tooltip: {
        trigger: "item",
        position: function (point, params, dom, rect, size) {
          let [x, y] = point;
          let { contentSize, viewSize } = size;

          let tooltipWidth = contentSize[0];
          let tooltipHeight = contentSize[1];
          let viewWidth = viewSize[0];
          let viewHeight = viewSize[1];

          let posX = x + 10;
          if (posX + tooltipWidth > viewWidth) {
            posX = x - tooltipWidth - 10;
          }
          if (posX < 0) {
            posX = 10;
          }

          let posY = y - tooltipHeight / 2;
          if (posY + tooltipHeight > viewHeight) {
            posY = viewHeight - tooltipHeight - 10;
          }
          if (posY < 0) {
            posY = 10;
          }

          return [posX, posY];
        },
        formatter: (params: any) => {
          console.log("params", params);
          if (params.componentType === "markArea") {
            // 自定义显示内容
            return `
            <div class="tooltip-content" style="max-width: 200px;">
              <p style="word-wrap: break-word; white-space: pre-wrap;">遥测数据: ${params.data.dataName}</p>
              <p>标记人员: ${params.data.userName}</p>
              <p>标记时间段: <br>
                <div style="text-align: center">
                ${params.data.beginTime}
                <br>-</br>
                ${params.data.endTime}
                </div>
                </p>
              <p>事件名称:${params.data.errorName}</p>
              <p>事件类型:${params.data.errorType}</p>
              <p style="word-wrap: break-word; white-space: pre-wrap;">事件描述:${params.data.errorDesc}</p>
            </div>
          `;
          } else if (params.componentType === "series") {
            console.log(
              "source_copy.value[params.dataIndex]",
              source_copy.value[params.dataIndex]
            );
            console.log("params.name", params.name);
            let content = "";
            const timePointDataArr = source_copy.value[params.dataIndex];
            for (let i = 0; i < timePointDataArr.length; i++) {
              let label = sourcetitle.value[i];
              let value = timePointDataArr[i];
              console.log(`label: ${label}, value: ${value}`);
              content += label + ":" + value + "<br/>";
            }
            // 显示点的时间
            return content;
          }
          return "";
        },
        textStyle: {
          fontSize: 12,
        },
      },
    };
    chart.value.setOption(options);
  }
  //点击在右侧展示标注信息
  chart.value.on("click", (params: any) => {
    console.log("params.data", params.data);
    //还原对应标注的信息
    ruleForm.dataName = params.data.dataName.join(", ");
    ruleForm.userName = params.data.userName;
    ruleForm.beginTime = params.data.beginTime;
    ruleForm.endTime = params.data.endTime;
    ruleForm.errorName = params.data.errorName;
    ruleForm.errorType = params.data.errorType;
    ruleForm.errorDesc = params.data.errorDesc;
    ruleForm.markColor = params.data.markColor;
    currentErrorId.value = params.data.errorId;
    debugger;
  });
});
</script>

<style scoped>
/* 左侧--参数区 */
.FilterParmsTree {
  height: 700px;

  display: block; /* 限制左侧高度并开启滚动条 */

  overflow-y: scroll;
}

.selection-box {
  position: absolute;
  background-color: rgba(0, 0, 255, 0.3); /* 蓝色半透明背景 */
  border: 1px dashed #000; /* 虚线边框 */
  pointer-events: none; /* 使框选痕迹不影响鼠标事件 */
}
.top-area {
  height: 50px;
  text-align: center;
  background-color: #f0f0f0; /* Adjust the background color as needed */
  padding: 5px; /* Adjust the padding as needed */
  display: flex;
  align-items: center;
  justify-content: center;
}

.top-area h1 {
  margin: 0;
  font-size: 18px; /* Adjust the font size as needed */
  color: #333; /* Adjust the font color as needed */
}

.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.large-input {
  width: 80%; /* Adjust the width as needed */
  height: 100px; /* Adjust the height as needed */
}

.BtnArea {
  display: flex;
  /* justify-content: center; */
  /* align-items: center; */
  gap: 10px; /* 设置按钮之间的间距 */
  padding: 10px; /* 可选：增加一些内边距 */
}

.option-input {
  width: 100%;
  margin-bottom: 8px;
}
</style>
